package com.baimifan.renovation.publicfrag;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.baimifan.renovation.R;
import com.baimifan.renovation.adapter.AddressAdapter;
import com.baimifan.renovation.manager.AddressManager;
import com.baimifan.renovation.tools.Shares;

import java.lang.ref.WeakReference;

public class AddressFragment extends Fragment {
    private Float w, h, widthPixels, heightPixels;
    private ListView address_lv;
    private AddressManager addressManager;
    private Shares shares;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_address, container, false);
        getDisplay();
        shares = new Shares(getActivity());
        address_lv = (ListView) view.findViewById(R.id.address_lv);
        addressManager = new AddressManager(new MyHandler(this));
        addressManager.citylist();
        return view;
    }

    private void getDisplay() {
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        widthPixels = Float.valueOf(metrics.widthPixels);
        heightPixels = Float.valueOf(metrics.heightPixels);
        w = widthPixels / 360;
        h = heightPixels / 640;
    }

    private class MyHandler extends Handler {
        WeakReference<AddressFragment> maddress;

        public MyHandler (AddressFragment addressFragment) {
            maddress = new WeakReference<AddressFragment>(addressFragment);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            AddressFragment address = maddress.get();
            switch (msg.what) {
                case 8:
                    address_lv.setAdapter(new AddressAdapter(addressManager.getcitylist(), w, h));
                    address_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            shares.setCityId(addressManager.getcitylist().get(position).getId() + "");
                            ((DialogFragmentWindow)getParentFragment()).current();
                        }
                    });
                    break;
            }
        }
    }

}
